package com.baizhi.service.impl;

import dao.teaDao;
import entity.category;
import entity.tea;
import org.apache.ibatis.session.SqlSession;
import com.baizhi.service.teaService;
import util.MyBatisUtils;
import util.PageBean;

import java.util.List;

public class teaServiceImpl implements teaService {
    @Override
    public PageBean<tea> page(PageBean<tea> p,String name) {
        SqlSession sqlSession = MyBatisUtils.openSession();
        try {
            teaDao dao = sqlSession.getMapper(teaDao.class);
            List<tea> list = dao.findAll(p.getStart(), p.getEnd(), name);
            int c = dao.count(name);
            p.setList(list);
            p.setCount(c);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            MyBatisUtils.close(sqlSession);
        }
        return p;
    }

    @Override
    public boolean add(tea a) {
        SqlSession session = MyBatisUtils.openSession();
        try {
            teaDao mapper = session.getMapper(teaDao.class);
            mapper.insert(a);
            session.commit();
            return  true;
        } catch (Exception e) {
            session.rollback();
            throw  new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
    }

    @Override
    public List<category> findoption() {
        SqlSession session = MyBatisUtils.openSession();
        teaDao dao = session.getMapper(teaDao.class);
        List<category> cate = dao.findCate();
        return cate;
    }

    @Override
    public boolean delete(int id) {
        SqlSession session = MyBatisUtils.openSession();
        try {
            teaDao mapper = session.getMapper(teaDao.class);
            mapper.delete(id);
            session.commit();
            return true;
        } catch (Exception e) {
            session.rollback();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
    }

    @Override
    public tea findone(int id) {
        SqlSession session = MyBatisUtils.openSession();
        teaDao dao = session.getMapper(teaDao.class);
        tea te = dao.findone(id);
        return te;
    }

    @Override
    public void update(tea t,int id) {
        SqlSession session = MyBatisUtils.openSession();
        try {
            teaDao mapper = session.getMapper(teaDao.class);
            t.setId(id);
            mapper.update(t);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            throw  new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
    }
}

